<template>
    <keep-alive :include="cachePages" :max="25">
        <router-view v-if="isRouterAlive" @hook:updated="$checkRequireItem"
          @hook:mounted="$checkRequireItem" />
      </keep-alive>
</template>
<script>
import { mapState } from 'vuex'
import debounce from 'lodash/debounce'
import { BUSINESS_MENU_TYPE } from '@/config/businessConfig'

export default {
  name: 'RouteView',
  data() {
    return {
      isRouterAlive: true,
      detailRouterName: ""
    }
  },
  computed: {
    ...mapState({
      businessSearchConditions: (state) => state.user.businessSearchConditions
    }),
    cachePages() {
      // console.log([...this.$store.state.tabInfo.cachePages, this.detailRouterName], 200)
      if(this.detailRouterName) {
       if( this.$store.state.tabInfo.cachePages.includes(this.detailRouterName)) {
         return  this.$store.state.tabInfo.cachePages
       } else {
         return [...this.$store.state.tabInfo.cachePages, this.detailRouterName]
       }
      }
      return [...this.$store.state.tabInfo.cachePages, this.detailRouterName]
    }
  },
  created() {
    const newValComponentName = this.$route.matched[this.$route.matched.length - 1].components.default?.name || this.$route.matched[this.$route.matched.length - 1].name
   if(!this.$route.meta.noTab) {
     this.detailRouterName = newValComponentName
   }
  },
  watch: {
    businessSearchConditions: {
      handler: debounce(function (val) {
        // 数据筛选值变化后重新加载路由页面
        this.$store.commit('tabInfo/CLEAN_CACHE_PAGE')
        this.isRouterAlive = false
        this.$nextTick(() => {
          this.isRouterAlive = true
          this.$checkRequireItem()
        })
      }, 100)
    },
    $route(newVal, oldVal) {
      // console.log(this.cachePages, 'cachePages', this.detailRouterName)
      if(newVal.path === oldVal.path && (!newVal.query.query || !oldVal.query.query)) {
        return
      }
      const newValComponentName = newVal.matched[newVal.matched.length - 1].components.default?.name || newVal.matched[newVal.matched.length - 1].name
      if (newVal.path === oldVal.path && newVal.query?.query !== oldVal.query?.query) {
        this.$store.commit('tabInfo/DEL_CACHE_PAGE', newValComponentName)
        this.isRouterAlive = false
        this.$nextTick(() => {
          this.isRouterAlive = true
          this.$checkRequireItem()
        })
      }
    }
  },
  methods: {
    // handleUpdated() {
    //   try {
    //     // setTimeout(() => {
    //     //   const requireDom = document.querySelectorAll('.ant-form-item-required')
    //     //   const requireDomArray = Array.from(requireDom)
    //     //   requireDomArray.forEach((item) => {
    //     //     item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
    //     //   })
    //     // }, 0)
    //   } catch {
    //   }
    // }
  }
}
</script>
